package it.pecuswap.backend.entities.base;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Example;

public class GenericBaseDAO<T extends Serializable> {

	private Session session;
	private Class<T> theClass;
	private Transaction transaction = null;

	@SuppressWarnings("unused")
	private GenericBaseDAO() {
	}

	public GenericBaseDAO(Class<T> theClass, boolean isSharedSession) {
		this.theClass = theClass;
		session = HibernateUtils.getInstance().getSession(isSharedSession);
	}

	@SuppressWarnings("unchecked")
	public T findById(long id) {
		return (T) session.get(theClass, id);
	}

	@SuppressWarnings("unchecked")
	public List<T> findAll() {
		return session.createQuery("from " + theClass.getName())
				.list();
	}
	
	@SuppressWarnings("unchecked")
	public List<T> findByExample(T instance){
		Criteria criteria = session.createCriteria(theClass);
		Example example = Example.create(instance);
		criteria.add(example);
		List<T> results = criteria.list();
		return results;
	}

	public void persist(T entity) {
		session.persist(entity);
	}

	public void save(T entity) {
		session.save(entity);
	}

	public void update(T entity) {
		session.merge(entity);
	}

	public void delete(T entity) {
		session.delete(entity);
	}

	public void deleteById(long entityId) {
		T entity = findById(entityId);
		delete(entity);
	}
	
	public void beginTransaction(){
		transaction = session.beginTransaction();
	}
	
	public void closeTransaction(){
		transaction.commit();
	}
	
	public void rollbackTransaction(){
		transaction.rollback();
	}

	protected final Session getSession() {
		return session;
	}

}
